<template>
  <div class="login">
    <main>
      <h2>用户登录</h2>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入手机号"
            size="large"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            v-model="ruleForm.pass"
            type="password"
            autocomplete="off"
            size="large"
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">去注册</el-button>
        </el-form-item>
      </el-form>
    </main>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { user_login } from "../api/api";
import { ElNotification } from "element-plus";
import "element-plus/es/components/notification/style/css";
var $router = useRouter();

// 过滤路由
import {filterRoutes} from '../utils/authorization'
import routes from '../router/routes'


var ruleForm = reactive({ phone: "", pass: ""});
var ruleFormRef = ref();

var resetForm = (ruleFormRef) => {
  $router.push({ path: "/register" });
};
// 表单验证
const validatePhone = (rule, value, callback) => {
  if (/^1[3-9]\d{9}$/.test(value) == false) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
};
const validatePass = (rule, value, callback) => {
  if (/^\d{4}$/.test(value) == false) {
    callback(new Error("请输入符合要求的密码,必须是4位数字"));
  } else {
    callback();
  }
};

const rules = reactive({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
});

// //点击"登录" 手动验证表单, 参数formEl是表单实例, validate是表单实例的方法, 用来验证整个表单.
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      user_login({phone:ruleForm.phone,pass:ruleForm.pass}).then((res) => {
        if (res.data.code == 200) {
          //登录成功, 跳转登录页
          ElNotification({
            title: "登录通知",
            message: res.data.msg,
            type: 'success',
          });
          localStorage.setItem('token',res.data.token);
          localStorage.setItem('userinfo',JSON.stringify(res.data.userinfo))
          // =================以下两步必须写在登陆成功并且保存token及userinfo之后,
          // =================跳转首页之前过滤出当前用户有权限访问的业务路由
          var accessRoutes = filterRoutes(routes,res.data.userinfo.role.permissions)
          console.log(accessRoutes);
          // 将过滤出来的路由  动态添加到router中
          accessRoutes.forEach((route)=>{
            $router.addRoute(route)  //循环一次，添加一条路由
          })

           //$router.addRoutes(accessRoutes); //Vue2中可以一次性添加所有路由.
          $router.push("/");
        }else{
            //弹框
            ElNotification({
              title: '登录通知',
              message: res.data.msg,
              type: 'error',
            })
        }
      });
    }else{
         return false
    }
  });
};

</script>

<style lang="scss">
* {
  padding: 0;
  margin: 0;
}
.login {
  border: 1px solid transparent;
  background: url("../assets/bj.png");
  background-size: cover;
  width: 100%;
  height: 100vh;
  main {
    border-radius: 10px;
    width: 400px;
    background-color: white;
    margin: 180px auto;
    padding: 20px;
    box-sizing: border-box;
    h2 {
      text-align: center;
      margin: 10px auto;
    }
    form {
      width: 90%;
      margin: 0 auto;
    }
    .el-form-item__content {
      justify-content: space-around;
    }
  }
}
</style>